<script setup>
import { showToast } from 'vant';
import { useRoute } from 'vue-router';
import router from "@/router/index.js";
import useCountdown from "@/hooks/useCountdown.js";
import { formatDateTime, formatPrice } from "@/utils/index.js";
import {getOrderDetails, getOrderLogistics, getReorder, confirmReceiptOfGoods, deleteOrder, orderConfig, cancelOrder} from "@/api/order.js";
const route = useRoute();
import { useI18n} from 'vue-i18n';
const { t } = useI18n();
import useSettingStore from '@/store/modules/setting'
import Pay from '../../shopping/pay.vue'
const {proxy} = getCurrentInstance()
const currency = ref(useSettingStore().global.currencySymbol || '')
const STATUS_TEXT = {
  '-2': t('order.refundSuccessful'),
  '-1': t('order.cancelled'),
  '0': t('order.due'),
  '1': t('order.goodsWaitingToBeSent'),
  '2': t('order.waitToBeReceived'),
  '3': t('order.completed')
};

const orderId = ref(route.query.id) // 订单ID
const stepsData = ref([
  {
    type: 1,
    title: t('order.submitAnOrder'),
    description: '',
  },
  {
    type: 4,
    title: t('order.goodsWaitingToBeSent'),
    description: '',
  },
  {
    type: 5,
    title: t('order.waitToBeReceived'),
    description: '',
  },
  {
    type: 6,
    title: t('order.transactionCompleted'),
    description: '',
  },
]);

const logs = ref([])
// 获取订单详情
const remainingTime = ref('');
const orderDetail = ref({
  logs: []
}) // 订单详情数据
const statusText = ref('')
async function getDetailInfo(load) {
  try {
    let res = await getOrderDetails(orderId.value);
    orderDetail.value = res.data;
    statusText.value = STATUS_TEXT[orderDetail.value.status] || '' // 订单状态
    const { status } = res.data
    for (let i = 0; i < stepsData.value.length; i++) {
      let matchedData = orderDetail.value.logs.find(item => item.operateType === stepsData.value[i].type);
      if (matchedData) {
        stepsData.value[i].description = formatDateTime(matchedData.createTime);
      }
    }
    if (status === 0) {
      remainingTime.value = useCountdown(orderDetail.value.time); // 订单倒计时
    } else {
      resumePayment.value = false
      clearTimer()
    }
    // 订单待收货状态获取物流信息
    if (orderDetail.value.status === 2) {
      getLogisticsInformation()
    }
  } catch (err) {
  } finally {
  }
}
// 获取订单物流信息
const logisticsInfo = ref({})
async function getLogisticsInformation() {
  try {
    let res = await getOrderLogistics(orderDetail.value.deliveryId);
    logisticsInfo.value = res.data;
  } catch (err) {}
}
// 获取再次购买信息
const loadingBtn = ref(false)
async function getRePurchaseInfo() {
  loadingBtn.value = true
  try {
    let res = await getReorder(orderId.value);
    console.log(res.data, 'res')
    let cartIdsString = res.data.cartId.join(","); // 转换为字符串
    loadingBtn.value = false
    router.push({path:'/shopping', query: {
        cartIds: cartIdsString
      }})
  } catch (err) {}
}
// 订单评论
function goToOrderComment(id) {
  router.push(`/order-comment?id=${orderDetail.value.id}`)
}
// 确认收货
const confirmLoading = ref(false)
const showConfirm = ref(false)
function confirmGoods() {
  confirmLoading.value = true
  confirmReceiptOfGoods(orderId.value).then(res => {
    showToast(t('order.confirmReceiptSuccess'))
    confirmLoading.value = false
    confirmLoading.value = false
    router.push({path:'/order'})
  }).catch(() => {
    showToast(t('order.failedToConfirmReceipt'))
  })
}
// 删除订单
const delShow = ref(false)
const delLoading = ref(false)
function clickDeleteOrder() {
  delLoading.value = true
  deleteOrder(orderDetail.value.id).then(() => {
    showToast(t('order.successfullyDeleted'))
    router.push({path:'/order'})
  }).catch(() => message.error(t('order.deletionFailure')))
}

// 取消订单
const cancelShow = ref(false)
const cancelLoading = ref(false)
function clickCancelOrder() {
  cancelLoading.value = true
  cancelOrder(orderDetail.value.id).then(() => {
    showToast(t('order.cancelSuccessfully'))
    cancelLoading.value = false
    router.push({path:'/order'})
  }).catch(() => {
    showToast(t('order.cancellationFailure'))
    cancelLoading.value = false
  })
}

// 继续付款
const procedure = ref(1)
const tabList = computed(() => {
  const status = 0
  return [
    { label: ft('toRoder'), isFinish: true },
    { label: ft('pay'), isFinish: !!status },
    { label: ft('paySuceess'), isFinish: !!status }
  ]
})

const compRef = ref(null)
// 订单心跳
const orderTimer = ref(null)
const resumePayment = ref(route.query.pay)
if (resumePayment) {
  getOrderConfig()
}
function clickPay() {
  if (resumePayment.value) {
    compRef.value.toPay()
    if (!orderTimer.value) orderTimer.value = setInterval(() => { getDetailInfo(false) }, 5000)
  } else {
    resumePayment.value = true
    getOrderConfig()
  }
}
// 清除定时器、心跳
function clearTimer () {
  clearInterval(orderTimer.value)
  orderTimer.value = null
}

// 订单规则配置
const orderRule = ref({})
const query = ref({
  orderId: orderId.value
})
function getOrderConfig () {
  orderConfig().then(r => {
    orderRule.value = r.data
  })
}

// 显示摘要
const summaryPopup = ref(false)
function showSummary() {
  summaryPopup.value = !summaryPopup.value
}

function ft(field) {
  return proxy.$t(`commodity.${field}`)
}
// 申请售后
function applyForAfterSales() {
  // router.push({path:'/applyAfterSales', query: {
  //     id: item.value.id
  //   }})
}
onMounted(() => {
  getDetailInfo(true)
})
</script>

<template>
  <div class="p-center">
    <h3>{{t('order.orderDetails')}}</h3>
    <div class="main-con w-width">
      <div class="receipt-info">
<!--        <h4>{{t('order.receivingInfo')}}</h4>-->
        <div class="top-state">
          <span>{{statusText}}</span>
          <span>{{remainingTime.remainingTime}}</span>
        </div>
        <div class="receipt-box">
          <div class="receipt-userName">{{orderDetail.firstName}} {{orderDetail.lastName}}</div>
          <div class="receipt-address">
            <div class="receipt-address-detail">{{orderDetail.addressDetail}}</div>
            <div class="receipt-address-contact">{{orderDetail.userPhone}}，{{t('order.postcode')}}({{orderDetail.postCode}})</div>
          </div>
          <div class="receipt-country">{{orderDetail.country}}</div>
        </div>
      </div>
      <div class="order-detail">
        <div class="left-box">
          <div v-if="orderDetail.status === 0 && resumePayment">
<!--            <div class="tab-box">-->
<!--              <div :gap="24">-->
<!--                <div v-for="(it, i) in tabList"-->
<!--                     :key="i"-->
<!--                     :class="['tab-item', it.isFinish?'active':'']">-->
<!--                  {{i+1}}.{{it.label}}-->
<!--                </div>-->
<!--              </div>-->
<!--            </div>-->
            <Pay ref="compRef" :order-rule="orderRule" :query="query"></Pay>
          </div>
          <div v-else>
<!--            <a-steps labelPlacement="vertical" :current="orderDetail.logs.length" :items="stepsData" />-->
            <div class="listing">
              <div class="listing-top">
                <div class="listing-left">
                  <div class="listing-tit">{{t('order.commodityList')}}</div>
<!--                  <div class="listing-num">{{t('order.quantity')}}</div>-->
                </div>
<!--                <div class="listing-total">{{t('order.subtotal')}}</div>-->
              </div>
              <div class="list-product">
                <div class="product-item" v-for="item in orderDetail.details">
                  <div class="product-left">
                    <div class="product-img">
                      <img :src="item.image" class="pic-img default-img">
                      <div class="product-info">
                        <div class="product-tit-sku">
                          <div class="product-tit">{{item.productName}}</div>
                          <div class="product-sku">
                            <span class="sku-tit">{{t('order.sku')}}：</span>
                            <span class="sku-value">{{item.sku}}</span>
                          </div>
                        </div>
                        <div class="money-quantity">
                          <div class="product-amount">{{currency}}{{formatPrice(item.originalPrice)}}</div>
                          <div class="product-num">x{{item.num}}</div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="logistics" v-if="orderDetail.status === 2">
              <h4>{{t('order.logisticsInfo')}}</h4>
              <div class="logistics-box">
                <div class="logistics-tit">
                  <div class="logistics-companies">{{t('order.logisticsCompany')}}：<b>{{orderDetail.deliveryName}}</b></div>
                  <div class="tracking-number">{{t('order.waybillNumber')}}：<b>{{orderDetail.deliveryId}}</b></div>
                </div>
                <div class="timeline">
                  <ul class="time-axis" :class="{ 'is-done': index === 0 }" v-for="(item,index) in logisticsInfo" :key="index">
                    <li>{{ item.key_stage }}</li>
                    <li>{{ item.time_iso }}</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="action-buttons">
      <div class="action-center">
        <div class="action-price">
          <div class="total-order">
            <div class="product-total">{{t('order.totalNum')}}：{{currency}}{{formatPrice(orderDetail.payPrice)}}</div>
          </div>
          <div class="order-summary" @click="showSummary">{{t('order.orderSummary')}}
            <van-icon name="arrow-down" /></div>
        </div>
        <div class="btn-box">
          <div class="btn-item" v-if="orderDetail.canComment" @click="goToOrderComment">{{t('order.comment')}}</div>
          <div class="btn-item" @click="delShow = true" v-if="orderDetail.status === -1 || orderDetail.status === 3">{{t('order.deleteAnOrder')}}</div>
          <div class="btn-item ant-popconfirm" v-if="orderDetail.status === -1 || orderDetail.status === 3" @click="getRePurchaseInfo">
            {{t('order.repurchase')}}
          </div>
          <div class="btn-item" @click="cancelShow = true" v-if="orderDetail.status === 0">{{t('order.cancelAnOrder')}}</div>
          <!--          申请售后-->
<!--          <div class="ant-popconfirm btn-item" @click="applyForAfterSales" v-if="orderDetail.status === 1 || orderDetail.status === 2">{{t('order.applySalesService')}}</div>-->
          <div class="ant-popconfirm btn-item" @click="clickPay" v-if="orderDetail.status === 0">{{resumePayment ? t('commodity.quiclPay') : t('order.immediatePayment')}}</div>
          <div class="ant-popconfirm btn-item" v-if="orderDetail.status === 2" @click="showConfirm = true">{{t('order.confirmGoods')}}</div>
        </div>
      </div>
    </div>
    <van-popup v-model:show="summaryPopup" position="bottom" :style="{ padding: '24px 16px 90px 16px'}">
      <div class="orders-summary">
        <h4>{{t('order.orderSummary')}}</h4>
        <div class="order-id">
          <span>{{t('order.orderNumber')}}</span>
          <span>{{orderDetail.orderCode}}</span>
        </div>
        <div class="order-amount">
          <div class="flex-box">
            <span class="label">{{t('order.grossCommodityPrice')}}</span>
            <span class="value">$ {{formatPrice(orderDetail.totalPrice)}}</span>
          </div>
          <div class="flex-box">
            <span class="label">{{t('order.promotionalOffer')}}</span>
            <span class="value">-$ {{formatPrice(orderDetail.couponPrice)}}</span>
          </div>
          <div class="flex-box">
            <span class="label">{{t('commodity.toOffset')}}</span>
            <span class="value">-$ {{formatPrice(orderDetail.integralDeduct)}}</span>
          </div>
          <div class="flex-box">
            <span class="label">{{t('order.freight')}}</span>
            <span class="value">$ {{orderDetail.totalPostage}}</span>
          </div>
          <div class="flex-box">
            <span class="label">{{t('order.commission')}}</span>
            <span class="value">$ {{orderDetail.taxation}}</span>
          </div>
        </div>
        <div class="pocket-amount">
          <div class="flex-box">
            <span class="label">{{t('order.actualAmountPaid')}}</span>
            <span class="value">$ {{formatPrice(orderDetail.payPrice)}}</span>
          </div>
        </div>
      </div>
    </van-popup>
    <!--    删除订单弹窗-->
    <van-popup v-model:show="delShow" :style="{ padding: '16px', width: '85%' }">
      <div class="popup-box">
        <h3>{{t('order.whetherToDelete')}}</h3>
        <div class="btn-box">
          <van-button class="add-btn s-btn" @click="delShow = false">{{t('order.cancel')}}</van-button>
          <van-button :loading="delLoading" class="s-btn" @click="clickDeleteOrder">{{t('order.affirm')}}</van-button>
        </div>
      </div>
    </van-popup>
    <!--    取消订单弹窗-->
    <van-popup v-model:show="cancelShow" :style="{ padding: '16px', width: '85%' }">
      <div class="popup-box">
        <h3>{{t('order.whetherToCancelOrder')}}</h3>
        <div class="btn-box">
          <van-button class="add-btn s-btn" @click="cancelShow = false">{{t('order.cancel')}}</van-button>
          <van-button :loading="cancelLoading" class="s-btn" @click="clickCancelOrder">{{t('order.affirm')}}</van-button>
        </div>
      </div>
    </van-popup>
    <!--    确认收货弹窗-->
    <van-popup v-model:show="showConfirm" :style="{ padding: '16px', width: '85%' }">
      <div class="popup-box">
        <h3>{{t('order.confirmReceiptOfGoods')}}</h3>
        <div class="btn-box">
          <van-button class="add-btn s-btn" @click="showConfirm = false">{{t('order.cancel')}}</van-button>
          <van-button :loading="confirmLoading" class="s-btn" @click="confirmGoods">{{t('order.affirm')}}</van-button>
        </div>
      </div>
    </van-popup>
<!--    <div class="delete-modal">-->
<!--      <a-modal-->
<!--          v-model:open="openValue"-->
<!--          title=""-->
<!--          @ok="cancel"-->
<!--          :centered="true"-->
<!--          :footer="null"-->
<!--      >-->
<!--        <div class="delete-box">-->
<!--          <h3>{{t('order.whetherToDelete')}}</h3>-->
<!--          <div class="delete-order">-->
<!--            <div class="btn-box">-->
<!--              <van-button class="add-btn s-btn" @click="cancel">{{t('order.cancel')}}</van-button>-->
<!--              <van-button :loading="delLoading" class="s-btn" @click="clickDeleteOrder(orderDetail.id)">{{t('order.deleteAnOrder')}}</van-button>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
<!--      </a-modal>-->
<!--    </div>-->
  </div>
</template>

<style scoped lang="scss">
.p-center {
  padding: 0 16px;
  h3 {
    font-weight: 500;
    font-size: 18px;
    color: #262626;
  }
  .main-con {
    .receipt-info {
      margin-top: 20px;
      .top-state {
        height: 36px;
        line-height: 36px;
        background: #262626;
        padding: 0 16px;
        border-radius: 2px 2px 0px 0px;
        font-weight: 500;
        font-size: 14px;
        color: #FFFFFF;
        display: flex;
        justify-content: space-between;
        span:last-child {
          font-weight: 400;
        }
      }
      .receipt-box {
        border-radius:0 0 2px 2px;
        border: 1px solid #8C8C8C;
        font-size: 12px;
        padding: 16px;
        .receipt-userName {
          font-weight: 600;
          color: #262626;
          margin-bottom: 10px;
        }
        .receipt-address {
          width: 100%;
          color: #262626;
          font-weight: 400;
          margin-bottom: 12px;
          .receipt-address-detail {
            margin-bottom: 5px;
          }
        }
        .receipt-country {
          flex: 1;
          color: #262626;
          font-weight: 400;
        }
      }
    }
    .order-detail {
      padding-bottom: 100px;
      .left-box {
        width: 100%;
        .tab-box {
          margin-bottom: 24px;
          .tab-item {
            flex: 1;
            font-size: 16px;
            border-bottom: 2px #8c8c8c solid;
            color: #8c8c8c;
            padding-bottom: 8px;
            &.active {
              border-color: #262626;
              color: #262626;
            }
          }
        }
      }
      .listing {
        margin-top: 20px;
        .listing-top {
          display: flex;
          font-weight: 600;
          font-size: 14px;
          color: #262626;
          border-bottom: 1px solid #E5E5E5;
          padding-bottom: 10px;
          margin-bottom: 15px;
          justify-content: space-between;
          .listing-left {
            width: 100%;
            display: flex;
            .listing-tit {
              width: 100%;
            }
          }
          .listing-total {
            flex: 1;
            text-align: right;
          }
          .listing-tit {
            width: 100%;
          }
        }
        .list-product {
          .product-item {
            width: 100%;
            margin-bottom: 16px;
            padding-bottom: 16px;
            border-bottom: 1px solid #E5E5E5;
            .product-left {
              width: 100%;
              display: flex;
              .product-img {
                width: 100%;
                display: flex;
                img {
                  width: 98px;
                  height: 110px;
                  margin-right: 12px;
                }
              }
              .product-amount {
                flex: 1;
                display: flex;
                flex-flow: column-reverse;
              }
              .product-info {
                color: #262626;
                font-size: 14px;
                display: flex;
                flex-flow: column;
                justify-content: space-between;
                flex: 1;
                .product-tit {
                  font-weight: 600;
                  margin-bottom: 15px;
                }
                .product-sku {
                  font-weight: 400;
                  display: flex;
                  align-items: center;
                  .sku-tit {
                    font-size: 12px;
                    color: #666666;
                  }
                  .sku-value {
                    color: #262626;
                  }
                }
                .money-quantity {
                  display: flex;
                  justify-content: space-between;
                }
                .product-amount {
                  color: #666666;
                }
              }
            }
          }
        }
      }
      .logistics {
        border: 1px solid #8C8C8C;
        border-radius: 2px;
        padding: 16px;
        h4 {
          font-size: 14px;
          margin: 0 0 10px 0;
        }
        .logistics-box {
          .logistics-tit {
            border-bottom: 1px solid #E5E5E5;
            height: 52px;
            margin-bottom: 20px;
            color: #8C8C8C;
            font-size: 14px;
            font-weight: 400;
            padding-bottom: 10px;
            b {
              color: #262626;
              font-weight: 400;
            }
            .logistics-companies {
              margin-bottom: 5px;
            }
            .tracking-number {
              margin-bottom: 10px;
            }
          }
          .timeline {
            .circular {
              border-radius: 50%;
              padding: 0;
              border: none;
              width: 10px;
              height: 10px;
              i {
                width: 10px;
                height: 10px;
                display: block;
                background: #BFBFBF;
                border-radius: 50%;
              }
            }
            .active {
              width: 16px;
              height: 16px;
              padding: 2px;
              box-sizing: border-box;
              border: 1px solid #262626;
              i {
                background: #262626;
              }
            }
            p {
              font-weight: 400;
              font-size: 14px;
              color: #262626;
            }
            .logistical-time {
              color: #8C8C8C;
            }
          }
        }
      }
    }
  }
  .orders-summary {
    .order-id {
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      color: #262626;
    }
    h4 {
      margin: 0 0 20px 0;
      font-size: 14px;
    }
    .order-amount {
      border-top: #E5E5E5 solid 1px;
      border-bottom: #E5E5E5 solid 1px;
      padding: 24px 0;
      margin: 24px 0;
      span {
        font-size: 14px;
        color: #262626;
        font-weight: 400;
      }
      .flex-box {
        margin-bottom: 8px;
        display: flex;
        justify-content: space-between;
      }
    }
    .pocket-amount {
      font-size: 14px;
      color: #262626;
      .flex-box {
        display: flex;
        justify-content: space-between;
      }
    }
  }
  .action-buttons {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 8px 16px;
    background: #fff;
    box-sizing: border-box;
    height: 68px;
    border-top: 1px solid #E5E5E5;
    display: flex;
    align-items: center;
    z-index: 9999;
    .action-center {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .action-price {
        .product-total {
          font-weight: 600;
          font-size: 14px;
          color: #262626;
        }
        .order-summary {
          font-weight: 400;
          font-size: 12px;
          color: #666666;
        }
      }
      .btn-box {
        display: flex;
      }
    }
    .btn-center {
      display: flex;
      align-items: center;
    }
    .btn-item {
      height: 44px;
      line-height: 44px;
      border: #262626 solid 1px;
      border-radius: 2px;
      text-align: center;
      font-size: 14px;
      cursor: pointer;
      margin-left: 8px;
      padding:0 5px;
    }
    .ant-popconfirm {
      background: #262626;
      color: #FFFFFF;
    }
  }
}
.delete-box {
  .delete-order {
    .btn-box {
      margin-top: 20px;
      display: flex;
      button {
        margin:5px;
      }
    }
  }
  .ant-btnant-btn {
    display: flex;
    align-items: center;
  }
}
.popup-box {
  width: 100%;
  h3 {
    font-weight: 500;
    font-size: 16px;
    color: #262626;
    text-align: center;
  }
  .btn-box {
    margin-top: 20px;
    display: flex;
    button {
      margin:5px;
      height: 44px;
    }
  }
}
/* 时间轴 */
.time-axis {
  color: #262626;
  position: relative;
  padding-left: 30px;
  list-style: none;
  &:before {
    position: absolute;
    margin-top: 8px;
    left: 4px;
    content: " ";
    height: 9px;
    width: 9px;
    border-radius: 50%;
    background-color: #e8e8e8;
  }
  &:after {
    position: absolute;
    top: 17px;
    left: 7px;
    bottom: -19px;
    content: " ";
    width: 1px;
    border-right: 1px solid #e8e8e8;
  }
  &:not(:first-child) {
    padding-top: 8px;
  }
  &:last-child {
    &:after {
      display: none;
    }
  }
  &.is-done {
    &:after {
      border-color: #BFBFBF;
    }
    &:before {
      background-color: #262626;
      box-shadow: #BFBFBF 0 0 10px;
    }
  }
}
</style>
